package com.fruit.controller.wap.goods;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fruit.constants.GoodsConstant;
import com.fruit.controller.base.BaseController;
import com.fruit.pojo.goods.Goods;
import com.fruit.resolver.DefiniteException;
import com.fruit.service.goods.GoodsManager;
import com.fruit.util.DateUtil;
import com.fruit.util.GoodsUtil;
import com.fruit.util.ResultInfo;

@Controller
@RequestMapping(value = "/wap/goods/")
public class GoodsController extends BaseController {

	@Autowired
	private GoodsManager goodsService;

	/**
	 * 打开商品详情页面
	 */
	@RequestMapping(value = "/detail", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView detail(HttpServletRequest request, HttpSession session) {
		String goodsId = request.getParameter("id");
		if (StringUtils.isBlank(goodsId)) {
			throw new DefiniteException("商品已经下架");
		}
		ModelAndView view = this.getModelAndView();
		Goods goods = goodsService.getGoodsDetail(Integer.parseInt(goodsId));// 根据商品id查询详情
		List<Map<String, Object>> priceRangeList = goodsService.getPriceRange(Integer.parseInt(goodsId));// 根据商品id查询价格范围
		List<Map<String, Object>> goodsParametersList = goodsService.getGoodsParameters(Integer.parseInt(goodsId));// 获取商品参数
		if (goods == null) {
			throw new DefiniteException("商品已经下架");
		} else {
			if (goods.getState().equals("00")) {// 商品已经下架
				throw new DefiniteException("商品已经下架");
			} else {
				if(goods.getIsAdvanceState().equals("01")){
					goods.setAdvanceStartTime(
							DateUtil.fomatDateTime(goods.getAdvanceStartTime(), "yyyy-MM-dd HH:mm:ss", "MM-dd"));
					goods.setAdvanceEndTime(
							DateUtil.fomatDateTime(goods.getAdvanceEndTime(), "yyyy-MM-dd HH:mm:ss", "MM-dd"));
					goods.setExpectDeliveryTime(
							DateUtil.fomatDateTime(goods.getExpectDeliveryTime(), "yyyy-MM-dd HH:mm:ss", "MM-dd"));
				}
				// 截取当前系统时间的 月和日
				SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
				String sysDate = sdf.format(new Date());
				String timeResult = null;
				if (StringUtils.isNotBlank(goods.getAdvanceStartTime())
						&& goods.getAdvanceStartTime().equals(sysDate)) {
					timeResult = GoodsConstant.START_ADVANCE;
				} else if (StringUtils.isNotBlank(goods.getAdvanceEndTime())
						&& goods.getAdvanceEndTime().equals(sysDate)) {
					timeResult = GoodsConstant.END_ADVANCE;
				} else if (StringUtils.isNotBlank(goods.getExpectDeliveryTime())
						&& goods.getExpectDeliveryTime().equals(sysDate)) {
					timeResult = GoodsConstant.EXPECT_DELIVERY;
				}
				String[] img = goods.getPicture().split(",");
				if (priceRangeList != null) {
					GoodsUtil.getGoodsPriceList(priceRangeList, goods.getMinShopNum());
				}
				//商品参数 名称处理
//				if(goodsParametersList != null){
//					for (int i = 0; i < goodsParametersList.size(); i++) {
//						Map<String, Object> goodsParameters = goodsParametersList.get(i);
//						String goodsParameterName = (String) goodsParameters.get("paramName");
//						
//						goodsParameters.put("minNum", goods.getMinShopNum());
//					}
//				}
				view.addObject("goods", goods);
				view.addObject("img", img);
				view.addObject("timeResult", timeResult);
				view.addObject("loginId", session.getAttribute("loginId"));
				view.addObject("priceRangeList", priceRangeList);
				view.addObject("goodsParametersList", goodsParametersList);
				view.setViewName("good/detail");
			}
		}
		return view;
	}

	/**
	 * 获取水果标签
	 * 
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/fruitLableList", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> fruitLableList(HttpServletRequest request, HttpSession session) {
		this.logBefore(logger, "获取水果标签");
		Map<String, Object> resultMap = new HashMap<>();
		Map<String, Object> papam = new HashMap<>();
		papam.put("goodsId", request.getParameter("id"));
		try {
			List<Map<String, Object>> fruitLableList = goodsService.getFruitLable(papam);// 获取水果标签
			resultMap.put("fruitLableList", fruitLableList);
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resultMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resultMap;
	}

	/**
	 * 获取当前登录人的默认地址
	 * 
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/defaultAddress", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> defaultAddress(HttpServletRequest request, HttpSession session) {
		this.logBefore(logger, "获取默认地址");
		Map<String, Object> resultMap = new HashMap<>();
		Map<String, Object> papam = new HashMap<>();
		papam.put("userId", session.getAttribute("loginId"));
		String userId = (String) session.getAttribute("userId");
		if (StringUtils.isBlank(userId)) {
			resultMap.put("address", "00");// 没有默认收货地址
		} else {
			try {
				Map<String, Object> defaultAddress = goodsService.getDefaultAddress(Integer.parseInt(userId));// 获取当前登录人的送货默认地址
				if (defaultAddress == null) {
					resultMap.put("address", "00");// 没有默认收货地址
				} else {
					resultMap.put("address", "01");// 有默认收货地址
					resultMap.put("defaultAddress", defaultAddress);
				}
			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
				resultMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
			}
		}
		this.logAfter(logger);
		return resultMap;
	}

	// 用户注册协议
	@RequestMapping(value = "/userPact", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView userPact(HttpServletRequest request, HttpSession session) {
		ModelAndView view = this.getModelAndView();
		view.setViewName("userpact");
		return view;
	}

	// 关于我们
	@RequestMapping(value = "/about", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView about(HttpServletRequest request, HttpSession session) {
		ModelAndView view = this.getModelAndView();
		view.setViewName("about");
		return view;
	}
}
